<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			* {
				margin: 0;
				padding: 0;
			}

			#myCan {
				display: block;
				margin: 0 auto;
				background-color: lightskyblue;
			}
		</style>
	</head>
	<body>
		<canvas id="myCan" width="800" height="400"></canvas>
		<button type="button" id="fs">反色</button>
		<button type="button" id="hb">黑白</button>
		<button type="button" id="hs">灰色</button>
		<script type="text/javascript">
			var oC = document.getElementById('myCan');
			var fs1 = document.getElementById('fs');
			var hb1 = document.getElementById('hb');
			var hs1 = document.getElementById('hs');
			var ctx = oC.getContext('2d');
			var oImg = new Image();
			oImg.src = 'images/3.png';
			oImg.onload = function() {
				ctx.drawImage(oImg, 0, 0, 400, 400);
				var imgData = ctx.getImageData(0, 0, 400, 400);
				var newImg = ctx.createImageData(400, 400);
				var w = newImg.width;
				var h = newImg.height;
				fs1.onclick = function() {
					console.log(1);
					fs(newImg, imgData, ctx);
				}

				hb1.onclick=function(){
					hb(newImg,imgData,ctx);
				}

				hs1.onclick = function() {
					hb(newImg, imgData, ctx);
				}

				for (i = 0; i < w * h; i++) {
					var r = imgData.data[4 * i];
					var g = imgData.data[4 * i + 1];
					var b = imgData.data[4 * i + 2];
					// 求颜色平均
					var avarge = (r + g + b) / 3;
					var a = 0;
					if (avarge > 128) {
						a = 255;
					} else {
						a = 0;
					}
					newImg.data[4 * i] = a;
					newImg.data[4 * i + 1] = a;
					newImg.data[4 * i + 2] = a;
					newImg.data[4 * i + 3] = 255;
				}
				ctx.putImageData(newImg, 400, 0);
			}

			function fs(newImg, imgData, ctx) {
				var w = newImg.width;
				var h = newImg.height;
				console.log(w, h);
				for (var i = 0; i < w * h; i++) {
					newImg.data[4 * i] = 255 - imgData.data[4 * i];
					newImg.data[4 * i + 1] = 255 - imgData.data[4 * i + 1];
					newImg.data[4 * i + 2] = 255 - imgData.data[4 * i + 2];
					newImg.data[4 * i + 3] = 255;

				}
				ctx.putImageData(newImg, 400, 0);
			}


			function hb(newImg, imgData, ctx) {
				var w = newImg.width;
				var h = newImg.height;
				for (i = 0; i < w * h; i++) {
					var r = imgData.data[4 * i];
					var g = imgData.data[4 * i + 1];
					var b = imgData.data[4 * i + 2];
					// 求颜色平均
					var avarge = (r + g + b) / 3;
					newImg.data[4 * i] = avarge;
					newImg.data[4 * i + 1] = avarge;
					newImg.data[4 * i + 2] = avarge;
					newImg.data[4 * i + 3] = 255;
				}
				ctx.putImageData(newImg, 400, 0);
			}
		</script>
	</body>
</html>
